package com.weidey.blogWeb.utils;


import com.weidey.blogWeb.mapper.WebArticleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.stream.Collectors;

@Component("syncFixViewConsistencyTask")
public class fixViewConsistency {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private WebArticleMapper articleMapper;

    public void syncArticleViews() {
        // 1. 获取所有文章的访问量增量
        Map<Object, Object> viewsMap = redisTemplate.opsForHash().entries("article:views");

        // 2. 批量更新数据库
        Map<Long, Integer> views = viewsMap.entrySet().stream()
                .collect(Collectors.toMap(
                        e -> Long.parseLong(e.getKey().toString()),
                        e -> Integer.parseInt(e.getValue().toString())
         ));
        articleMapper.updateViews(views);
        // 3. 清空Redis计数
        redisTemplate.delete("article:views");
    }



}
